<template>
  <eui-background type="common">
    <eui-navbar ref="EuiNavBar" :title="title" displayable="true"/>
    <eui-card hPadding="28">
      <view class="item-view">

        <eui-text :value="detailData.c_gcode" :name="detailData.c_gname" type="name2" title="商品"
                  cWidth="width: 100%"/>
        <eui-text :value="getName('rdsProviders', detailData.c_provider)" type="name2" title="供应商"
                  cWidth="width: 100%"/>
        <eui-text type="price2" title="采购件数" :value="detailData.c_n_pack" :valueStyle="showRightStyle"
                  :precision="3" cWidth="width: 50%"/>
        <eui-text type="price2" title="均重" :value="detailData.c_avg_weight" :valueStyle="showRightStyle"
                  :precision="3" cWidth="width: 50%"/>
        <eui-text type="price2" title="采购价格" :value="detailData.c_pt_pay" :valueStyle="showRightStyle"
                  :precision="3"/>
        <eui-text type="price2" title="最后进价" :value="detailData.c_last_pt_pay" :valueStyle="showRightStyle"
                  :precision="3"/>
        <eui-text type="price2" title="采购金额" :value="detailData.c_at_pay" :valueStyle="showRightStyle"
                  :precision="3"/>
        <eui-text type="price2" title="采购数量" :value="detailData.c_n_total_pur" :valueStyle="showRedStyle"
                  :precision="3"/>
      </view>
    </eui-card>
    <view class="footer-view" :style="{ height: listHeight + 'rpx' }">
      <scroll-view scroll-y="true" style="height: 100%;">
        <view style="display:flex;flex-direction: column">
          <eui-card hPadding="28" v-if="storeList && storeList.length > 0">
            <eui-swipe-action>
              <view :ref="'dataItem' + index" v-for="(item, index) in storeList" :key="index"
                    @click="onClickGdsInfo(item, index)">
                <eui-swipe-actionitem :ref="`swipeActionItem${index}`" :right-options="options" show="none"
                                      :auto-close="true" @change="change" @click="bindClick($event, index)">
                  <view class="item-view">
                    <eui-text :value="getName('rdsStores', item.c_store_id)" type="name2" title="机构"
                              cWidth="width: 100%"/>
                    <eui-text :value="getName('rdsWnos', item.c_wno)" type="name2" title="仓库"
                              cWidth="width: 100%"/>
                    <eui-text type="price2" title="已分配数量" :value="item.c_om_n" :valueStyle="showRightStyle"
                              :precision="3"/>
                    <eui-text type="price2" title="采购数量" :value="item.c_n_pur" :valueStyle="showRedStyle"
                              :precision="3"/>
                    <eui-text v-model="item.c_note" type="name2" title="备注"
                              cWidth="width: 100%; margin-bottom: 20rpx"/>
                  </view>
                </eui-swipe-actionitem>
              </view>
            </eui-swipe-action>
          </eui-card>
        </view>
      </scroll-view>
    </view>
    <eui-popup ref="storePopup" background-color="#f8f8f8" type="bottom" :mask-click="false">
      <view class="popup-content">
        <view style="padding: 20rpx 20rpx 0 20rpx">
          <view class="item-view">
            <eui-text :value="getName('rdsStores', currentStore.c_store_id)" type="name2" title="机构"
                      cWidth="width: 100%"/>
            <eui-text type="price2" title="昨日销售" :value="currentStore.c_day1" :valueStyle="showRightStyle"
                      :precision="3"/>
            <eui-text type="price2" title="前日销售" :value="currentStore.c_day2" :valueStyle="showRightStyle"
                      :precision="3"/>
            <eui-text type="price2" title="三日前销量" :value="currentStore.c_day3" :valueStyle="showRightStyle"
                      :precision="3"/>
            <eui-text type="price2" title="上周同期销量" :value="currentStore.c_day7" :valueStyle="showRightStyle"
                      :precision="3"/>
          </view>
          <eui-card-input v-model="currentStore.c_wno" title="仓库" placeholder="请选择仓库" type="textname"
                          right-icon-type="right" @icon-click="clickRight('c_wno')" required="true"
                          :name="getRelatedName('rdsWnos', currentStore.c_wno)" h-padding="0" alignType="left"/>
          <eui-card-input v-model="currentStore.c_n_pur" type="number" title="采购数量" h-padding="0" maxlength="9"
                          fieldName="c_n_pur" @confirm="validateDetail" ref="cardNInput"
                          alignType="left" :precision="3" required="true" placeholder="请输入数量"/>
          <eui-card-input v-model="currentStore.c_note" title="备注" fieldName="c_note" h-padding="0"
                          maxlength="100" alignType="left"/>
        </view>
      </view>
      <view class="popup-bottom flex-1 flex">
        <eui-button type="max2" title="关闭" singleTag="cancel" @buttonClick="buttonClick"/>
        <eui-button type="max" title="确认" singleTag="submit" @buttonClick="buttonClick"/>
      </view>
    </eui-popup>
    <view class="bottom-view flex-1 flex">
      <eui-button type="max2" title="保存" singleTag="confirm" @buttonClick="buttonClick"/>
      <eui-button type="max" title="增加分店" singleTag="addStore" @buttonClick="buttonClick"/>
    </view>
  </eui-background>
</template>

<script setup type="ts">
import {onMounted, ref, reactive} from "vue";
import {onLoad} from "@dcloudio/uni-app";
import {validateStores} from '@/hooks/useValidateMethod';
import service from "@/common/service";
import {getRdsUrl, rdsRequest,} from '@/hooks/rdsServices';
import {useMainStore} from "@/store/modules/store";
import {
  getRelatedName,
} from '../components/RelatedName.js';
import Enjoy from "@/common/enjoy";
import {calcAtInByPt} from '@/hooks/useCalculateMethod';
const rdsUrl = getRdsUrl();
const mainStore = useMainStore();
const listHeight = ref(300);
const sUserStore = ref('');
const sUserStoreName = ref('');
const sUser = ref('');
const title = ref('采购分店');
const options = ref([{
  text: '删除',
  style: {
    backgroundColor: '#F56C6C',
  }
}]);
const showRightStyle = ref('text-align: right');
const showRedStyle = ref('text-align: right;color: #FF4000;');
const detailData = ref({});
const storeList = ref([]);
let delList = reactive([]);
let newList = reactive([]);
let modifiedList = reactive([]);
const currentStore = ref({});
const currentStoreIndex = ref(0);
const mainData = ref({});
const c_gcode = ref('');
const c_gname = ref('');
const storePopup = ref(null);
const cardNInput = ref(null);
const isOpened = ref('none');

onMounted(() => {
  getListHeight()
})

// 获取列表高度
const getListHeight = async () => {
  await uni.getSystemInfo({
    success: function (res) { // res - 各种参数
      let info = uni.createSelectorQuery().select(".footer-view");
      info.boundingClientRect(function (data) { //data - 各种参数
        //获取列表高度
        let height = res.windowHeight - data.top;
        //转换rpx
        listHeight.value = height / (res.windowWidth / 750) - 100;
      }).exec()
    }
  });
};

onLoad(async (option) => {
  if (!option.c_id) {
    return;
  }
  mainData.value.c_id = option.c_id;
  c_gcode.value = option.c_gcode;
  c_gname.value = option.c_gname;
  service.enjoyShowLoading('正在加载...');
  await billQuery();
  service.enjoyHideLoading();
  await setDefault();
})

const setDefault = async (storeInfo) => {
  const {loginInfo} = mainStore;
  sUserStore.value = storeInfo?.sUserStore || loginInfo.sUserStore;
  sUserStoreName.value = storeInfo?.sUserStoreName || loginInfo.sUserStoreName;
  sUser.value = loginInfo.sUser;
  mainData.value.c_buyer_no = sUser.value;
  mainData.value.c_mk_userno = sUser.value;
  mainData.value.c_dc_store_id = sUserStore.value;
  mainData.value.c_mk_store_id = sUserStore.value;
}

const validateDetail = async (args) => {
  const {fieldName, oldValue, newValue} = args;
  switch (fieldName) {
    case 'c_n_pur':// 采购数量
      if (newValue >= 0 && newValue < 99999) {
        currentStore.value.c_n_pur = newValue;
      } else {
        if (oldValue) {
          cardNInput.value.inputValue = oldValue;
          currentStore.value.c_n_pur = oldValue;
        }
        await uni.showToast({
          duration: 2000,
          icon: 'none',
          title: '请输入0~99999的数'
        });
      }
      return;
  }
}

const onClickGdsInfo = (item, index) => {
  service.enjoyShowLoading('正在加载...');
  try {
    currentStoreIndex.value = index;
    currentStore.value = JSON.parse(JSON.stringify(item));
    currentStore.value.rowType = (currentStore.value.rowType === 1 || currentStore.value.rowType === undefined) ? 1 : 2;
    storePopup.value.open();
  } catch (error) {
    service.enjoyHideLoading();
  }
  service.enjoyHideLoading();

}

const buttonClick = async (t) => {
  let {singleTag} = t;
  switch (singleTag) {
    case 'confirm':
      service.enjoyShowLoading("正在保存...");
      await saveBill();
      await billQuery();
      service.enjoyHideLoading();
      break;
    case 'addStore':
      let params = Enjoy.GetDialogParms();
      params.CallBack = addStoreCallBack;
      params.SelectionType = "机构选择";
      params.SelectedItems = sUserStore.value;
      Enjoy.OpenDialog(params);
      break;
    case 'submit':
      if (currentStore.value.c_n_pur > 99999) {
        await uni.showToast({
          duration: 2000,
          icon: 'none',
          title: '请输入0~99999的数'
        });
        break;
      }
      let c_n_total_pur = 0;
      for (let i = 0; i < storeList.value.length; i++) {
        if (i === currentStoreIndex.value) {
          c_n_total_pur += Number(currentStore.value.c_n_pur);
        } else {
          c_n_total_pur += Number(storeList.value[i].c_n_pur);
        }
      }
      if (c_n_total_pur > 999999999) {
        await uni.showToast({
          duration: 2000,
          icon: 'none',
          title: '采购数量总和不能超过999999999'
        });
        break;
      }
      service.enjoyShowLoading("正在加载...");
      currentStore.value.rowType = (currentStore.value.rowType === 1 || currentStore.value.rowType === undefined) ? 1 : 2;
      storeList.value[currentStoreIndex.value] = currentStore.value;
      service.enjoyHideLoading();
      setTimeout(() => {
        storePopup.value.close();
      }, 300);
      detailData.value.c_n_total_pur = c_n_total_pur;
      detailData.value.c_at_pay = calcAtInByPt({c_pt: detailData.value.c_pt_pay, c_n: detailData.value.c_n_total_pur});
      break;
    case 'cancel':
      storePopup.value.close();
      break;
  }
}

const addStoreCallBack = async (e) => {
  let storeId = e.BackParms.Key;
  let storeName = e.BackParms.Value;
  const result = await validateStores(
      {fieldName: 'c_store_id', row: mainData.value, newValue: storeId},
      {ischecklimit: true, firstValueMode: true}
  );
  if (['2'].includes(result.c_type)) {
    // 更新机构信息
    sUserStoreName.value = storeName;
    sUserStore.value = storeId;
    mainData.value.c_mk_store_id = storeId;
    const itemIndex = storeList.value.findIndex(x => x.c_store_id === storeId);
    if (itemIndex == -1) {
      await storeQuery(storeId);
    }
  } else {
    await uni.showToast({
      duration: 2000,
      icon: 'none',
      title: '所选机构非分店！'
    });
    // setTimeout(() => {
    //   let params = Enjoy.GetDialogParms();
    //   params.CallBack = addStoreCallBack;
    //   params.SelectionType = "机构选择";
    //   params.SelectedItems = sUserStore.value;
    //   Enjoy.OpenDialog(params);
    // }, 300);
  }
}

const storeQuery = async (storeId) => {
  if (!storeId) {
    return;
  }
  service.enjoyShowLoading('正在加载...');
  const req = {
    WhereList: [
      {c_col: "c_gcode", c_oper: "等于", c_value: c_gcode.value, c_logic: "而且"},
      {c_col: "c_store_id", c_oper: "等于", c_value: storeId, c_logic: "而且"},
      {c_col: "c_store", c_oper: "等于", c_value: storeId, c_logic: "而且"},
    ],
  };
  const result = await rdsRequest(rdsUrl.scApi, 'SCIC公共服务', 'FetchRecSales', req, '5C1');
  // 根据result.ds.length是否大于0，决定是否从result.ds[0]中提取额外属性
  const additionalProps = result.ds.length > 0 ? {...result.ds[0]} : {
    c_day1: 0,
    c_day2: 0,
    c_day3: 0,
    c_day7: 0,
  };
  currentStore.value = {
    c_tenant_id: '',
    c_id: '',
    c_gsort: detailData.value.c_sort,
    c_sort: storeList.value.length + 1,
    c_store_id: storeId,
    c_wno: '00',
    c_gcode: c_gcode.value,
    c_n_orig_req: 0,
    c_n_req: 0,
    c_n_pur: 0,
    c_is_mch: '0',
    c_src_type: '0',
    c_req_type: '0', // 要货类型|0-采购补货、1-门店要货、2-客户要货
    c_note: '',
    rowType: 1,
    ...additionalProps
  };
  // 将currentStore添加到storeList
  storeList.value.push(JSON.parse(JSON.stringify(currentStore.value)));
  currentStoreIndex.value = storeList.value.length - 1;
  service.enjoyHideLoading();
}

const saveBill = async () => {
  if (storeList.value.length <= 0) {
    await uni.showToast({
      duration: 2000,
      icon: 'none',
      title: '请录入机构！'
    });
    return;
  }
  storeList.value.forEach(x => x.c_id = mainData.value.c_id)
  newList = storeList.value.filter(x => x.rowType === 1 || !x.hasOwnProperty('rowType'));
  modifiedList = storeList.value.filter(x => x.rowType === 2);
  const req = {
    NewList: [],
    ModifiedList: [mainData.value],
    DelList: [],
    TableName: "tb_po_fsh_po",
    PrimaryKeys: ["c_tenant_id", "c_id"],
    ChildData: [
      {
        ChildTableName: "tb_po_fsh_pog",
        ParentTableName: "tb_po_fsh_po",
        ChildColumnNames: ["c_id"],
        ParentColumnNames: ["c_id"],
        ChildSaveModel: {
          NewList: [],
          ModifiedList: [detailData.value],
          DelList: [],
          TableName: "tb_po_fsh_pog",
          PrimaryKeys: ["c_tenant_id", "c_id", "c_sort"],
        },
      },
      {
        ChildTableName: "tb_po_fsh_po_gs",
        ParentTableName: "tb_po_fsh_po",
        ChildColumnNames: ["c_id"],
        ParentColumnNames: ["c_id"],
        ChildSaveModel: {
          NewList: newList,
          ModifiedList: modifiedList,
          DelList: delList,
          TableName: "tb_po_fsh_po_gs",
          PrimaryKeys: ["c_tenant_id", "c_id", "c_sort", "c_gsort"]
        },
      }
    ],
    BillSet: {
      BillIdKeyValue: {
        key: "c_id",
        value: mainData.value.c_id
      },
      BillVariable: "",
      TableName: "tb_po_fsh_po",
      BillName: "生鲜采购单"
    },
  };
  await rdsRequest(rdsUrl.scApi, '生鲜采购单', 'EnjoyBillSaveNew', req, '5C1');
  await uni.showToast({
    duration: 2000,
    icon: 'none',
    title: `保存成功`
  });
  newList = [];
  modifiedList = [];
  delList = [];
}

const billQuery = async () => {
  if (!mainData.value.c_id) {
    return;
  }
  service.enjoyShowLoading('正在加载...');
  const req = {
    BillId: mainData.value.c_id,
  };
  const result = await rdsRequest(rdsUrl.scApi, '生鲜采购单', 'EnjoyBillQuery', req, '5C1');
  if (result.ds.length > 0) {
    mainData.value = result.ds[0];
    detailData.value = result.ds1.find(x => x.c_gcode === c_gcode.value) || {};
    detailData.value.c_gname = c_gname.value;
    storeList.value = result.ds2.filter(x => x.c_gcode === c_gcode.value) || [];
    storeList.value.forEach(x => x.rowType = 2);
  } else {
    await uni.showToast({
      duration: 2000,
      icon: 'none',
      title: '未查询到数据',
      mask: true,
    });
  }
}

const getName = (key, value) => {
  if (!value) {
    return ''
  }
  let list = [];
  value.split(',').map(item => {
    list.push("[" + item + "]" + (getRelatedName(key, item) || key));
  })
  return list.join(',');
}

const clickRight = (type) => {
  let param = '';
  switch (type) {
    case 'c_wno':
      param = 'wno&storeId=' + sUserStore.value;
      break;
  }
  uni.navigateTo({
    url: `../modals/index?type=${param}`
  });
}

const SelectionChanged = async (type, param) => {
  switch (type) {
    case 'wno':
      currentStore.value.c_wno = param.c_wno;
      break;
  }
}

const change = (e) => {
  isOpened.value = e;
}

const bindClick = (e, index) => {
  uni.showModal({
    title: ' 提示',
    content: '您确定要删除数据吗？',
    showCancel: true,
    success: async (res) => {
      if (res.confirm) {
        let deleteStore = storeList.value[index];
        if (deleteStore.rowType === 2) {
          delList.push(deleteStore);
        }
        storeList.value.splice(index, 1);
        detailData.value.c_n_total_pur = storeList.value.reduce((total, item) => total + item.c_n_pur, 0);
        detailData.value.c_at_pay = calcAtInByPt({c_pt: detailData.value.c_pt_pay, c_n: detailData.value.c_n_total_pur});
      }
    }
  });
}

defineExpose({
  SelectionChanged
});
</script>

<style lang="scss" scoped>
@import '../../../main.scss';

.extra-view {
  margin-right: 30rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 60rpx;
  height: 100%;
}

.footer-view {
  width: 100%;
  flex: 1;
}

.list-scroll {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}

.bottom-view {
  width: 100%;
  height: 100rpx;
  background: #FFFFFF;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  flex-direction: row;
}

.center-style {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  margin-right: 20rpx;
  //gap: 20rpx;
}

.gap-view {
  width: 20rpx;
  height: auto;
}

//内容行
.item-view {
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  align-items: center;
  margin-top: 16rpx;
  row-gap: 8rpx;
}

.button-view {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-top: 16rpx;
  row-gap: 8rpx;
}

.line-view {
  width: 100%;
  height: 1rpx;
  background: #EEEEEE;
  margin: 20rpx 0;
}

.popup-content {
  align-items: center;
  justify-content: left;
  flex-direction: column;
  padding: 0;
  width: 100%;
  background-color: #ffffff;
}

.popup-bottom {
  background: #ffffff;
  border-top: 1rpx solid $uni-line-color;
  display: flex;
  justify-content: center;
  padding: 20rpx;
}
</style>
